<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response as Psr7Response;

class UserController extends Controller
{
    public function login(AuthorizationRequest $originRequest, AuthorizationServer $server, ServerRequestInterface $serverRequest)
    {
        $client_id = config('passport.client_id');
        $client_secret = config('passport.client_secret');

        if (!$client_id || !$client_secret)
            return $this->error(1, '未配置passport_id或secret', 400, [$client_id, $client_secret]);

        $username = ($serverRequest->getParsedBody())['username'];
        $password = ($serverRequest->getParsedBody())['password'];
        // 组装passport的鉴权参数
        $serverRequest = $serverRequest->withParsedBody([
            'grant_type' => 'password',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'username' => $username,
            'password' => $password,
            'scope' => '*',
        ]);
        try {
            $response = $server->respondToAccessTokenRequest($serverRequest, new Psr7Response)->withStatus(201);
            $user = (new User)->findForPassport($username)->first();
            $user->last_login_at = date('Y-m-d H:i:s');
            $user->save();
            return $response;
        } catch (OAuthServerException $e) {
            return $this->error(1, __('auth.failed'), 401);
        }
    }

    public function info(Request $request)
    {
        return $this->success($request->user());
    }
}
